package com.vimi8.ebb.api.ebb;

import com.vimi8.ebb.configuration.HttpResponseEntity;
import com.vimi8.ebb.configuration.OAuth2AuthenticationImpl;
import com.vimi8.ebb.dto.LogisticsBusinessDTO1;
import com.vimi8.ebb.dto.LogisticsDTO;
import com.vimi8.ebb.model.*;
import com.vimi8.ebb.model.Error;
import com.vimi8.ebb.service.ElectricityBusinessService;
import com.vimi8.ebb.service.EnumCategoryService;
import com.vimi8.ebb.service.GeoCodingsService;
import com.vimi8.ebb.service.LogisticsService;
import com.vimi8.ebb.util.JxlExcelUtil;
import com.vimi8.ebb.util.PagesUtil;
import com.vimi8.ebb.util.SubStringUtil;
import io.swagger.annotations.ApiParam;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 物流信息
 * Created by xiehuang on 2017/1/19.
 */

@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringCodegen", date = "2016-09-12T05:17:54.080Z")
@Controller
public class LogisticsApiController implements LogisticsApi {
    private static final org.slf4j.Logger logger = LoggerFactory.getLogger("LogisticsApiController");
    @Autowired
    private LogisticsService logisticsService;
    @Autowired
    private EnumCategoryService enumCategoryService;
    @Autowired
    private GeoCodingsService geoCodingsService;
    @Autowired
    private ElectricityBusinessService electricityBusinessService;

    @Override
    public HttpResponseEntity<Paginator<List<LogisticsDTO>>> getLogistics(
            @ApiParam(value = "当前页码", required = true) @RequestParam(value = "start", required = true) int start,
            @ApiParam(value = "每页大小", required = true) @RequestParam(value = "size", required = true) int size,
            @ApiParam(value = "地址编码", required = false) @RequestParam(value = "addressCode", required = false) String addressCode,
            @ApiParam(value = "网点名称", required = false) @RequestParam(value = "branchName", required = false) String branchName
    ) {
        logger.info("requestUrl=" + "/logistics/");
        String code = addressCode;
        String orgClass = OAuth2AuthenticationImpl.ClientOrgClass();
        String clientAddressCode = electricityBusinessService.getClientAddressCode(OAuth2AuthenticationImpl.openId());
        if("org_ebb_city".equals(orgClass)||"org_ebb_county".equals(orgClass)){
            clientAddressCode = electricityBusinessService.getClientAddressCode(OAuth2AuthenticationImpl.openId());

        }

        if (StringUtils.isEmpty(addressCode)&&null != clientAddressCode && !"".equals(clientAddressCode)) {
            GeoCodings geoCodings = geoCodingsService.getGeoCodingsById(clientAddressCode);
            code = SubStringUtil.separateGeoCodeByProduct(geoCodings.getId(), geoCodings.getRegionLever() + 1 + "");
        }
        //获取物流信息的总数
        int count = logisticsService.getLogisticsCount(code, branchName);
        //分页查询物流信息
        List<Logistics> logisticses = logisticsService.getLogistics((start - 1) * size, size, code, branchName, "", "");
        List<LogisticsDTO> logisticsDTOs = new ArrayList<>();
        for (Logistics logistics : logisticses) {
            EnumCategory enumCategory = enumCategoryService.getEnumCategoryById(logistics.getAffiliationId());//根据ID查询机构信息
            LogisticsDTO logisticsDTO = new LogisticsDTO();
            logisticsDTO.fill(logistics);//填充父类
            if (!StringUtils.isEmpty(enumCategory)) {
                logisticsDTO.setAffiliationName(enumCategory.getCategoryName());//设置机构名称
            }
            String branchAddress = geoCodingsService.getAddressWhole(logistics.getBranchAddressCode());//获取完整地址
            logisticsDTO.setBranchAddress(branchAddress);
            String shippingAddress = geoCodingsService.getAddressWhole(logistics.getShippingAddressCode());//获取完整地址
            logisticsDTO.setShippingAddress(shippingAddress);
            String deliveryArea = geoCodingsService.getAddressWhole(logistics.getDeliveryAreaCode());//获取完整地址
            logisticsDTO.setDeliveryArea(deliveryArea);
            logisticsDTOs.add(logisticsDTO);
        }
        //设置分页信息
        PagesUtil pagesUtil = new PagesUtil();
        pagesUtil.setPageSize(size);
        pagesUtil.setTotalCount(count);
        Paginator<List<LogisticsDTO>> paginator = new Paginator<List<LogisticsDTO>>(start, size, pagesUtil.getTotalPage(), count, logisticsDTOs);
        return new HttpResponseEntity<Paginator<List<LogisticsDTO>>>(paginator, HttpStatus.OK);
    }

    @Override
    public HttpResponseEntity<Paginator<List<LogisticsBusinessDTO1>>> getLogisticsLatest(
            @ApiParam(value = "当前页码", required = true) @RequestParam(value = "start", required = true) int start,
            @ApiParam(value = "每页大小", required = true) @RequestParam(value = "size", required = true) int size,
            @ApiParam(value = "地址编码", required = false) @RequestParam(value = "addressCode", required = false) String addressCode,
            @ApiParam(value = "网点名称", required = false) @RequestParam(value = "branchName", required = false) String branchName,
            @ApiParam(value = "统计时间", required = false) @RequestParam(value = "statisticsTime", required = false) String statisticsTime,
            @ApiParam(value = "统计结束时间", required = false) @RequestParam(value = "endTime", required = false) String endTime
    ) {
        logger.info("requestUrl=" + "/logistics/latest");
        String code = addressCode;
        String orgClass = OAuth2AuthenticationImpl.ClientOrgClass();
        String clientAddressCode = electricityBusinessService.getClientAddressCode(OAuth2AuthenticationImpl.openId());

        if("org_ebb_city".equals(orgClass)||"org_ebb_county".equals(orgClass)){
            clientAddressCode = electricityBusinessService.getClientAddressCode(OAuth2AuthenticationImpl.openId());

        }

        if (StringUtils.isEmpty(addressCode)&&null != clientAddressCode && !"".equals(clientAddressCode)) {
            GeoCodings geoCodings = geoCodingsService.getGeoCodingsById(clientAddressCode);
            code = SubStringUtil.separateGeoCodeByProduct(geoCodings.getId(), geoCodings.getRegionLever() + 1 + "");
        }
        logger.info("orgClass="+orgClass+",clientAddressCode="+clientAddressCode+",code="+code);
        //获取物流信息的总数
        int count = logisticsService.getLogisticsLatestCount(code, branchName, statisticsTime,endTime);
        logger.info("count="+count);
        //分页查询物流信息
        List<LogisticsBusinessDTO1> logisticsBusinessDTO1s = logisticsService.getLogisticsLatest((start - 1) * size, size, code, branchName, statisticsTime,endTime, "", "DESC");
        logger.info("index="+(start - 1) * size+",branchName="+branchName+",addresscode="+code+",statisticsTime="+statisticsTime);
        logger.info("logisticsBusinessDTO1s="+logisticsBusinessDTO1s);
        for (LogisticsBusinessDTO1 logisticsBusinessDTO1 : logisticsBusinessDTO1s) {
            EnumCategory enumCategory = enumCategoryService.getEnumCategoryById(logisticsBusinessDTO1.getAffiliationId());//根据ID查询机构信息
            if (!StringUtils.isEmpty(enumCategory)) {
                logisticsBusinessDTO1.setAffiliationName(enumCategory.getCategoryName());//设置机构名称
            }
            String branchAddress = geoCodingsService.getAddressWhole(logisticsBusinessDTO1.getBranchAddressCode());//获取完整地址
            logisticsBusinessDTO1.setBranchAddress(branchAddress);
            String deliveryArea = geoCodingsService.getAddressWhole(logisticsBusinessDTO1.getDeliveryAreaCode());//获取完整地址
            logisticsBusinessDTO1.setDeliveryArea(deliveryArea);
        }
        //设置分页信息
        PagesUtil pagesUtil = new PagesUtil();
        pagesUtil.setPageSize(size);
        pagesUtil.setTotalCount(count);
        Paginator<List<LogisticsBusinessDTO1>> paginator = new Paginator<List<LogisticsBusinessDTO1>>(start, size, pagesUtil.getTotalPage(), count, logisticsBusinessDTO1s);
        return new HttpResponseEntity<Paginator<List<LogisticsBusinessDTO1>>>(paginator, HttpStatus.OK);
    }

    @Override
    public HttpResponseEntity<LogisticsDTO> getLogisticsById(@ApiParam(value = "id", required = true) @PathVariable(value = "id", required = true) String id) {
        Logistics logistics = logisticsService.getLogisticsById(id);
        EnumCategory enumCategory = enumCategoryService.getEnumCategoryById(logistics.getAffiliationId());
        LogisticsDTO logisticsDTO = new LogisticsDTO();
        logisticsDTO.fill(logistics);
        if (!StringUtils.isEmpty(enumCategory)) {
            logisticsDTO.setAffiliationName(enumCategory.getCategoryName());
        }
        String branchAddress = geoCodingsService.getAddressWhole(logistics.getBranchAddressCode());//获取完整地址
        logisticsDTO.setBranchAddress(branchAddress);
        String shippingAddress = geoCodingsService.getAddressWhole(logistics.getShippingAddressCode());//获取完整地址
        logisticsDTO.setShippingAddress(shippingAddress);
        String deliveryArea = geoCodingsService.getAddressWhole(logistics.getDeliveryAreaCode());//获取完整地址
        logisticsDTO.setDeliveryArea(deliveryArea);
        return new HttpResponseEntity<LogisticsDTO>(logisticsDTO, HttpStatus.OK);
    }

    @Override
    public HttpResponseEntity<Object> importLogistics(@RequestParam("file") MultipartFile file) {
        logger.info("requestUrl=" + "/logistics/import");
        logger.info("upload file param=" + file.toString());
        Error error = new Error();
        if (file == null) {
            error.error("upload file can't be empty").errorDescription("import error");
            return new HttpResponseEntity<Object>(error, HttpStatus.MULTI_STATUS);
        }
        List<Logistics> logisticses = readLogistics(file);
        int count = 0;
        try {
            count = logisticsService.batchLogistics(logisticses);
            count+=logisticsService.batchLogisticsBusiness(logisticses);
        } catch (Exception e) {
            logger.error(e.getMessage());
            error.error("internal server error").errorDescription(e.getLocalizedMessage());
            return new HttpResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new HttpResponseEntity<Object>(HttpStatus.OK);
    }

    @Override
    public void exportLogistics(

            @ApiParam(value = "地址编码", required = false) @RequestParam(value = "addressCode", required = false) String addressCode,
            @ApiParam(value = "网点名称", required = false) @RequestParam(value = "branchName", required = false) String branchName,
            @ApiParam(value = "时间", required = false) @RequestParam(value = "statisticsTime",required = false) String statisticsTime,
            @ApiParam(value = "时间", required = false) @RequestParam(value = "endTime",required = false) String endTime,
            HttpServletResponse response) {
        logger.info("requestUrl=" + "/logistics/export");

        String code = "";
        if (null != addressCode && !"".equals(addressCode)) {
            GeoCodings geoCodings = geoCodingsService.getGeoCodingsById(addressCode);
            code = SubStringUtil.separateGeoCodeByProduct(addressCode, geoCodings.getRegionLever() + 1 + "");
        }

        //查询物流信息
        List<Logistics> logisticses = logisticsService.getLogisticsLatestForExport( code, branchName, statisticsTime,endTime, null,null);
        List<LogisticsDTO> logisticsDTOs = new ArrayList<>();
        for (Logistics logistics : logisticses) {
            EnumCategory enumCategory = enumCategoryService.getEnumCategoryById(logistics.getAffiliationId());//根据ID查询机构信息
            LogisticsDTO logisticsDTO = new LogisticsDTO();
            logisticsDTO.fill(logistics);//填充父类
            if (!StringUtils.isEmpty(enumCategory)) {
                logisticsDTO.setAffiliationName(enumCategory.getCategoryName());//设置机构名称
            }
            String branchAddress = geoCodingsService.getAddressWhole(logistics.getBranchAddressCode());//获取完整地址
            logisticsDTO.setBranchAddress(branchAddress);
            String shippingAddress = geoCodingsService.getAddressWhole(logistics.getShippingAddressCode());//获取完整地址
            logisticsDTO.setShippingAddress(shippingAddress);
            String deliveryArea = geoCodingsService.getAddressWhole(logistics.getDeliveryAreaCode());//获取完整地址
            logisticsDTO.setDeliveryArea(deliveryArea);
            logisticsDTOs.add(logisticsDTO);
        }

        Error error = new Error();

        String[] headers = {
                "机构名称",
                "网点名称",
                "网点地址",
                "月发出量(件)",
                "月发入量(件)",
                "员工人数(人)",
                "车辆数",
                "统计日期",
                "联系人",
                "联系方式",
                "配送范围",
                "收货地址"};
        String[] methods = {
                "getAffiliationName",
                "getBranchName",
                "getBranchAddress",
                "getMonthOutAmount",
                "getMonthInAmount",
                "getStaffs",
                "getVehicles",
                "getTradeStatisticsTime",
                "getPrincipal",
                "getContact",
                "getDeliveryArea",
                "getShippingAddress"
        };

        try {
            String filename = "物流信息";
            String filepath = "./" + filename;

            JxlExcelUtil.writeExcelObject(filepath, headers, methods, logisticsDTOs, response);

            InputStream is = new FileInputStream(filepath);
            response.reset();
            response.setContentType("application/msexcel;charset=UTF-8");
            response.addHeader("Content-Disposition",
                    "attachment;   filename=\"" + new String((filename).getBytes("gbk"), "iso8859-1") + ".xls\"");
            byte[] b = new byte[100];
            int len;
            while ((len = is.read(b)) > 0) {
                response.getOutputStream().write(b, 0, len);
            }
            is.close();
        } catch (Exception e) {
        }
    }

    @Override
    public HttpResponseEntity<String> addLogistics(@ApiParam(value = "物流信息", required = true) @RequestBody Logistics logistics) {
        int count = 0;
        try {
            logistics.setId(UUID.randomUUID().toString());
            String addressCode=logistics.getBranchAddressCode();
            String orgClass=OAuth2AuthenticationImpl.ClientOrgClass();
            // logger.info("clientId="+clientId+",openId="+openId+"orgClass="+orgClass);
            String clientAddressCode=null;
            // 根据电商办对应的区县 查询区县下的数据
            if("org_ebb_city".equals(orgClass)||"org_ebb_county".equals(orgClass)){
                clientAddressCode = electricityBusinessService.getClientAddressCode(OAuth2AuthenticationImpl.openId());

            }
            if (StringUtils.isEmpty(addressCode)&&null!=clientAddressCode&&!"".equals(clientAddressCode)){
                //GeoCodings geoCodings=geoCodingsService.getGeoCodingsById(clientAddressCode);
                addressCode=clientAddressCode;
                logger.info("addressCode="+addressCode);
            }
            logistics.setBranchAddressCode(addressCode);
            count = logisticsService.insertLogistics(logistics);
         // count+=  logisticsService.insertLogisticsBusiness();
        } catch (Exception e) {
            Error error = new Error().error("add error").errorDescription("add error");
            new HttpResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new HttpResponseEntity<String>(count + "", HttpStatus.OK);
    }

    @Override
    public HttpResponseEntity<String> addLogisticsBusiness(@ApiParam(value = "业务量Model", required = true) @RequestBody LogisticsBusiness logisticsBusiness) {
        int count = 0;
        try {
            logisticsBusiness.setId(UUID.randomUUID().toString());
            count = logisticsService.insertLogisticsBusiness(logisticsBusiness);
        } catch (Exception e) {
            Error error = new Error().error("add error").errorDescription("add error");
            new HttpResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new HttpResponseEntity<String>(count + "", HttpStatus.OK);
    }

    @Override
    public HttpResponseEntity<String> updateLogistics(@ApiParam(value = "物流信息", required = true) @RequestBody Logistics logistics) {
        int count = 0;
        try {
            count = logisticsService.updateLogistics(logistics);
        } catch (Exception e) {
            Error error = new Error().error("update error").errorDescription("update error");
            new HttpResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new HttpResponseEntity<String>(count + "", HttpStatus.OK);
    }

    @Override
    public HttpResponseEntity<String> deleteLogistics(@ApiParam(value = "物流信息id", required = true) @RequestParam(value = "id", required = true) String id) {
        int count = 0;
        try {
            count = logisticsService.deleteLogistics(id);
        } catch (Exception e) {
            Error error = new Error().error("delete error").errorDescription("delete error");
            new HttpResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new HttpResponseEntity<String>(count + "", HttpStatus.OK);
    }

    @Override
    public HttpResponseEntity<String> deleteSelectedAllLogistics(@ApiParam(value = "物流信息ids", required = true) @RequestBody(required = true) String ids) {
        int count = 0;
        try {
            count = logisticsService.deleteLogisticsByIds(ids);
            return new HttpResponseEntity<String>(count+"",HttpStatus.OK);
        }catch (Exception e){
            return new HttpResponseEntity(new Error().error("sql error").errorDescription(e.getMessage()),HttpStatus.SERVICE_UNAVAILABLE);
        }
    }

    @Override
    public HttpResponseEntity<String> deleteLogisticsBusiness(@ApiParam(value = "物流业务量id", required = true) @PathVariable(value = "id", required = true) String id) {
        int count = 0;
        try {
            count = logisticsService.deleteLogisticsBusiness(id);//删除物流业务量
        } catch (Exception e) {
            Error error = new Error().error("delete error").errorDescription("delete error");
            new HttpResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new HttpResponseEntity<String>(count + "", HttpStatus.OK);
    }

    /**
     * 读取物流信息
     *
     * @param multipartFile
     * @return
     */
    private List readLogistics(MultipartFile multipartFile) {
        List<Logistics> list = new ArrayList<Logistics>();
        try {
            //打开文件
            Workbook book = Workbook.getWorkbook(multipartFile.getInputStream());
            //取得第一个sheet
            Sheet sheet = book.getSheet(0);

            //取得行数
            int rows = sheet.getRows();
            logger.info("rows==" + rows);

            for (int i = 2; i < rows; i++) {
                Logistics logistics = new Logistics();
                //物流信息ID
                logistics.setId(UUID.randomUUID().toString());

                //归属机构ID
                String affiliationName = sheet.getCell(0, i).getContents();
                if (!StringUtils.isEmpty(affiliationName)&&!"null".equals(affiliationName.trim())) {
                    List<EnumCategory> categories = enumCategoryService.getCategoryByName(affiliationName.trim());
                    if (categories.size() > 0) {
                        logistics.setAffiliationId(categories.get(0).getId());
                    }
                }


                //网点名称
                String branchName = sheet.getCell(1, i).getContents();
                if (!StringUtils.isEmpty(branchName)&&!"null".equals(branchName)) {
                    logistics.setBranchName(branchName);
                }

                //网点地址
                String branchAddress = sheet.getCell(2, i).getContents();
                if (!StringUtils.isEmpty(branchAddress)&&!"null".equals(branchAddress)) {
                    logistics.setBranchAddress(branchAddress);
                }

                //网点地址编码
                String branchAddressCode = sheet.getCell(3, i).getContents();
                if (!StringUtils.isEmpty(branchAddressCode)&&!"null".equals(branchAddressCode)) {
                    branchAddressCode= JxlExcelUtil.geoMap.get(branchAddressCode.trim());
                    logistics.setBranchAddressCode(branchAddressCode);
                }

                //月发出量
                String monthOutAmount = sheet.getCell(4, i).getContents();
                if (!StringUtils.isEmpty(monthOutAmount)&&!"null".equals(monthOutAmount)) {
                    logistics.setMonthOutAmount(Integer.parseInt(monthOutAmount));
                }

                //月发入量
                String monthInAmount = sheet.getCell(5, i).getContents();
                if (!StringUtils.isEmpty(monthInAmount)&&!"null".equals(monthInAmount)) {
                    logistics.setMonthInAmount(Integer.parseInt(monthInAmount));
                }

                //员工数
                String staffs = sheet.getCell(6, i).getContents();
                if (!StringUtils.isEmpty(staffs)&&!"null".equals(staffs)) {
                    logistics.setStaffs(Integer.parseInt(staffs));
                }

                //配送范围
                String deliveryArea = sheet.getCell(7, i).getContents();
                if (!StringUtils.isEmpty(deliveryArea)&&!"null".equals(deliveryArea)) {
                    logistics.setDeliveryArea(deliveryArea);
                    //设置配送范围编码
                    Address address = convertAddress(branchAddress);
                    List<GeoCodings> geoCodingses = geoCodingsService.getAddressInfo(address);
                    if (geoCodingses.size() > 0) {
                        GeoCodings geoCodings = geoCodingses.get(geoCodingses.size() - 1);
                        logistics.setDeliveryAreaCode(geoCodings.getId());
                    }
                }

                //联系人
                String principal = sheet.getCell(8, i).getContents();
                if (!StringUtils.isEmpty(principal)&&!"null".equals(principal)) {
                    logistics.setPrincipal(principal);
                }

                //联系方式
                String contact = sheet.getCell(9, i).getContents();
                if (!StringUtils.isEmpty(contact)&&!"null".equals(contact)) {
                    logistics.setContact(contact);
                }

                //交易统计时间
                String tradeStatisticsTime = sheet.getCell(10, i).getContents();
                if (!StringUtils.isEmpty(tradeStatisticsTime)&&!"null".equals(tradeStatisticsTime)) {
                    logistics.setTradeStatisticsTime(tradeStatisticsTime);
                }

                //车辆数
                String vehicles = sheet.getCell(11, i).getContents();
                if (!StringUtils.isEmpty(vehicles)&&!"null".equals(vehicles)) {
                    logistics.setVehicles(Integer.parseInt(vehicles));
                }

                //运单编号
                String shippingOrderId = sheet.getCell(12, i).getContents();
                if (!StringUtils.isEmpty(shippingOrderId)&&!"null".equals(shippingOrderId)) {
                    logistics.setShippingOrderId(shippingOrderId);
                }

                //收货地址
                String shippingAddress = sheet.getCell(13, i).getContents();
                if (!StringUtils.isEmpty(shippingAddress)&&!"null".equals(shippingAddress)) {
                    logistics.setShippingAddress(shippingAddress);
                    //设置收货地址编码
                    Address address = convertAddress(branchAddress);
                    List<GeoCodings> geoCodingses = geoCodingsService.getAddressInfo(address);
                    if (geoCodingses.size() > 0) {
                        GeoCodings geoCodings = geoCodingses.get(geoCodingses.size() - 1);
                        logistics.setShippingAddressCode(geoCodings.getId());
                    }
                }
                if (!StringUtils.isEmpty(logistics.getBranchName())) {
                    list.add(logistics);
                }

            }
            //关闭文件
            book.close();
        } catch (BiffException e) {
            logger.error("数据读取出错！", e);
        } catch (IOException e) {
            logger.error("数据读取出错！", e);
        }
        return list;
    }


    /**
     * 将一个字符串表示的地址准换为地址对象
     *
     * @param text 字符串表示的地址
     * @return
     */
    private Address convertAddress(String text) {
        //构建一个正则表达式
        StringBuilder regExp = new StringBuilder();
        regExp.append("([\u4e00-\u9fa5\\w]+?[省]||.)");
        regExp.append("([\u4e00-\u9fa5\\w]+?[市]||.)");
        regExp.append("([\u4e00-\u9fa5\\w]+?[区县]||.)");
        regExp.append("([\u4e00-\u9fa5\\w]+?[乡镇]||.)");
        regExp.append("([\u4e00-\u9fa5\\w]+?[居村委会]||.)");

        Pattern pattern = Pattern.compile(regExp.toString());
        Matcher matcher = pattern.matcher(text);
        Address address = new Address();
        if (matcher.find()) {
            address.setProvence(matcher.group(1));
            address.setCity(matcher.group(2));
            address.setCounty(matcher.group(3));
            address.setVillage(matcher.group(4));
            address.setBurg(matcher.group(5));
        }
        return address;
    }

}
